package com.smartcruise.main.mainFragment.tools.globalSearch;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.smartcruise.R;
import com.smartcruise.data.Contacts;
import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.task.TaskWithMapActivity;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.ToastUtils;
import com.smartcruise.util.customView.CircleImage;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.RealmResults;

/**
 * Created by FengChaoQun
 * on 2018/4/9 0009
 */

public class GlobalSearchAdapter extends BaseAdapter {

    private RealmResults<CruiseData> cruiseDataList;
    private RealmResults<Contacts> contactsList;
    private Context context;

    public GlobalSearchAdapter(RealmResults<CruiseData> cruiseDataList, RealmResults<Contacts> contactsList, Context context) {
        this.cruiseDataList = cruiseDataList;
        this.contactsList = contactsList;
        this.context = context;
    }

    @Override
    public int getCount() {
        int count = 0;
        if (isHasContacts()) {
            count += contactsList.size() + 1;
        }
        if (isHasTask()) {
            count += cruiseDataList.size() + 1;
        }
        return count;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        switch (getItemViewType(position)) {
            case 0:
                return buildTitleView(convertView, position);
            case 1:
                return buildContactView(convertView, position);
            case 2:
                return buildTaskView(convertView, position);
        }
        return convertView;
    }

    @Override
    public int getViewTypeCount() {
        return 3;
    }

    /**
     * description:先显示联系人 后显示任务
     * 0表示标题
     * 1表示联系人
     * 2表示任务
     */

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return 0;
        }
        if (isHasTask() && isHasContacts()) {
            if (position <= contactsList.size()) {
                return 1;
            } else if (position == contactsList.size() + 1) {
                return 0;
            } else {
                return 2;
            }
        } else if (isHasContacts()) {
            return 1;
        } else if (isHasTask()) {
            return 2;
        }
        return 0;
    }

    private boolean isHasContacts() {
        return ListUtils.isHaveContent(contactsList);
    }

    private boolean isHasTask() {
        return ListUtils.isHaveContent(cruiseDataList);
    }

    private View buildTitleView(View convertView, int position) {
        TitleViewHolder viewHolder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_title, null);
            viewHolder = new TitleViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (TitleViewHolder) convertView.getTag();
        }
        if (isHasContacts() && position == 0) {
            viewHolder.text.setText("联系人");
        } else {
            viewHolder.text.setText("任务");
        }
        return convertView;
    }

    private View buildContactView(View convertView, int position) {
        ContactViewHolder viewHolder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_contact, null);
            viewHolder = new ContactViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ContactViewHolder) convertView.getTag();
        }
        final Contacts contact = contactsList.get(position - 1);
        viewHolder.name.setText(contact.getUserName());
        viewHolder.phone.setText(contact.getPhoneNumber());
        viewHolder.departmentName.setText("这里是部门信息");
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final NormalDialog dialog = new NormalDialog(getContext());
                dialog.content("呼叫" + contact.getUserName() + "?")
                        .btnText("取消", "呼叫")
                        .setOnBtnClickL(new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                            }
                        }, new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getPhoneNumber()));
                                if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    ToastUtils.showShort(getContext(), "没有授权拨打电话，请在设置界面授权");
                                    return;
                                }
                                getContext().startActivity(intent);
                            }
                        });
                dialog.show();
            }
        });

        viewHolder.category.setVisibility(View.GONE);
        return convertView;
    }

    private View buildTaskView(View convertView, int position) {
        TaskViewHolder viewHolder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_main_task, null);
            viewHolder = new TaskViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (TaskViewHolder) convertView.getTag();
        }

        int frontSize = isHasContacts() ? contactsList.size() + 1 : 0;
        final CruiseData cruiseData = cruiseDataList.get(position - 1 - frontSize);
        viewHolder.taskName.setText(cruiseData.getName());
        viewHolder.taskType.setText(cruiseData.getType());

        if (cruiseData.isFromNet()) {//从服务器拉取的数据
            viewHolder.time.setText("完成时间" + TimeUtils.getSimpleTimeString(cruiseData.getActualStopDate()));
            if (CruiseContract.AUDITED == cruiseData.getAuditStatus()) {//审核完成的任务
                if (cruiseData.isAuditSuccess()) {
                    viewHolder.taskStatus.setText(cruiseData.getAuditResult());
                } else {
                    if (cruiseData.isDataChanged()) {
                        switch (cruiseData.getUploadStatus()) {
                            case 0:
                                viewHolder.taskStatus.setText("被驳回");
                                break;
                            case 1:
                                viewHolder.taskStatus.setText("(被驳回)已上传概要数据");
                                break;
                            case 2:
                                viewHolder.taskStatus.setText("(被驳回)已上传");
                                break;
                        }
                    } else {
                        viewHolder.taskStatus.setText("被驳回");
                    }
                }
            } else {
                viewHolder.taskStatus.setText("已上传");
            }
        } else {//本地任务
            viewHolder.time.setText("预耗时" + cruiseData.getCostTime() + "小时");
            if (!cruiseData.isCopyData()) {
                viewHolder.taskStatus.setText("");
            } else {
                if (CruiseContract.TASK_IS_END.equals(cruiseData.getStatusInApp())) {//结束的任务显示上传状态
                    switch (cruiseData.getUploadStatus()) {
                        case 0:
                            viewHolder.taskStatus.setText("待上传");
                            break;
                        case 1:
                            viewHolder.taskStatus.setText("已上传概要数据");
                            break;
                        case 2:
                            viewHolder.taskStatus.setText("已上传");
                            break;
                    }
                } else {
                    viewHolder.taskStatus.setText(cruiseData.getStatusInApp());
                }
            }
        }

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TaskWithMapActivity.start(context, cruiseData.getId());
            }
        });

        return convertView;
    }

    static class TitleViewHolder {
        @BindView(R.id.text)
        TextView text;

        TitleViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class ContactViewHolder {
        @BindView(R.id.category)
        TextView category;
        @BindView(R.id.headImage)
        CircleImage headImage;
        @BindView(R.id.name)
        TextView name;
        @BindView(R.id.phone)
        TextView phone;
        @BindView(R.id.departmentName)
        TextView departmentName;

        ContactViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    public Context getContext() {
        return context;
    }

    static class TaskViewHolder {
        @BindView(R.id.taskName)
        TextView taskName;
        @BindView(R.id.taskType)
        TextView taskType;
        @BindView(R.id.time)
        TextView time;
        @BindView(R.id.taskStatus)
        TextView taskStatus;

        TaskViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
